package org.ting.book.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.mapper.BookMapper;
import org.ting.book.mapper.BorrowMapper;
import org.ting.book.model.BookInfo;
import org.ting.book.model.BorrowRecord;
import org.ting.book.model.Result;

import java.util.List;

@Service
public class BorrowService {
    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    BookMapper bookMapper;
    ResultGenerator success = new ResultSuccess();
    ResultGenerator fail = new ResultFail();
    @Transactional
    public Result<?> borrowBook(Integer userId, Integer bookId) {
        //获取图书信息
        BookInfo bookInfo = bookMapper.getBookById(bookId);
        if(bookInfo.getCount() <= 0) {
            return fail.getResult("库存不足");
        }
        if(!bookInfo.getStatus()) {
            return fail.getResult("该图书不可借阅");
        }
        //更新库存-1
        bookInfo.setCount(bookInfo.getCount() - 1);
        bookMapper.updateBook(bookInfo);

        //插入借阅记录
        if(borrowMapper.insert(userId, bookId) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }

    public List<BorrowRecord> getRecordByUserId(Integer userId) {
        return borrowMapper.getBorrowByUserId(userId);
    }

    @Transactional
    public Result<?> returnBook(Integer recordId) {
        //查询借阅记录
        BorrowRecord borrowRecord = borrowMapper.getRecordById(recordId);

        //修改图书库存+1
        BookInfo bookInfo = bookMapper.getBookById(borrowRecord.getBookId());
        bookInfo.setCount(bookInfo.getCount() + 1);
        bookMapper.updateBook(bookInfo);

        //修改稿借阅记录
        borrowRecord.setIsReturn(true);
        if(borrowMapper.updateIsReturn(borrowRecord) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }
}
